package cn.liwq.study.demo.java.agent.raw;

import java.lang.instrument.Instrumentation;

/**
 * <p>Project: demo-common </p>
 * 
 * <p>Function:  </p>
 * 
 * <p>Description:  </p>
 * 
 * @author weiqiang.li
 * 
 * @date 2019/2/12
 * 
 * @version 1.0
 */
public class MyAgent {

    public static void premain(String agentArgs, Instrumentation inst) {
        System.out.println("[Agent] premain method");
        String clsName = "cn.liwq.study.demo.java.agent.raw.MyTask";
        transformClass(clsName, inst);
    }

    private static void transformClass(String clsName, Instrumentation inst) {
        Class<?> targetCls = null;
        ClassLoader targetClassLoader = null;
        try {
            targetCls = Class.forName(clsName);
            targetClassLoader = targetCls.getClassLoader();
            transform(targetCls, targetClassLoader, inst);
            return;
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        for (Class<?> clazz : inst.getAllLoadedClasses()) {
            if (clazz.getName().equals(clsName)) {
                targetCls = clazz;
                targetClassLoader = targetCls.getClassLoader();
                transform(targetCls, targetClassLoader, inst);
                return;
            }
        }

        throw new RuntimeException("Failed to find class " + clsName);

    }

    private static void transform(Class<?> clazz, ClassLoader classLoader, Instrumentation inst) {
        TaskTransformer dt = new TaskTransformer(clazz.getName(), classLoader);
        inst.addTransformer(dt, true);
        try {
            inst.retransformClasses(clazz);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
